package com.vogue.api.common.security.config;

import com.vogue.api.common.security.exception.AuthExceptionEntryPoint;
import com.vogue.api.common.security.exception.CustomAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * 资源服务配置
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    AuthExceptionEntryPoint authExceptionEntryPoint;
    @Autowired
    CustomAccessDeniedHandler customAccessDeniedHandler;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(authExceptionEntryPoint)
                .accessDeniedHandler(customAccessDeniedHandler);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable()
                .headers().frameOptions().sameOrigin()
                .and()
                //登录配置
                .formLogin()
                .loginPage("/login")
                .and()
                .formLogin().permitAll()
                .and()
                //不需要登录授权的的资源
                .authorizeRequests()
                .antMatchers("/images/favicon.ico","/**/*.mp3", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js","/**/*.map", "/**/*.woff2").permitAll()
                .antMatchers("/static/**","/css/**","/js/**","/images/**","/vendor/**","/index","/im/**","/jitsi/**","/captcha","/login3").permitAll()
                .antMatchers("/test/**","/api/public/welcome","/api/public/getNearbyMerchant/**","/api/public/register-upload-image","/api/user/register","/api/user/sendSmsCode").permitAll()
                .and()
                //需要登录授权才能访问的资源
                .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")  // admin角色才能访问
                .antMatchers("/api/**").hasRole("USER") // admin或user角色才能访问
                .anyRequest().authenticated();//其他请求要登录才能访问

    }

}

